<?php

class NewsLogic {

	function save (&$newsItem)
	{
		$newsItemDao = new NewsItemDAO();

		if ($newsItem->id == 0)
		{
			$newsItem->create_date = date("Y-m-d H:i:s");
		}

		return $newsItemDao->save($newsItem) == 1;
	}

	function load ($id)
	{
		$newsItemDao = new NewsItemDAO();

		return $newsItemDao->get($id);
	}

	function delete ($id)
	{
		$newsItemTypeMapDao = new NewsItemTypeMapDAO();
		foreach($newsItemTypeMapDao->findWhere("news_item_id = $id") as $newsItemTypeMap)
		{
			$newsItemTypeMapDao->delete($newsItemTypeMap);
		}

		$newsItemDao = new NewsItemDAO();
		$newsItemDao->delete(new NewsItem($id));
	}

	function loadTags ($newsItemId)
	{
		$newsItemTypeMapDao = new NewsItemTypeMapDAO();

		$codeLookupDao = new CodeLookupDAO();

		$results = $codeLookupDao->findBySQL("select cl.* from code_lookup cl, news_item_type_map nit " .
					" where cl.name = 'news_item_tag' and cl.code_key = nit.news_item_tag " .
					"   and nit.news_item_id = $newsItemId");

		$final = array();
		foreach ($results as $codeLookupObj)
		{
			array_push($final, $codeLookupObj->value);
		}

		return $final;
	}

	function saveTags ($newsItemId, $tagArray)
	{
		$newsItemTypeMapDao = new NewsItemTypeMapDAO();

		foreach($newsItemTypeMapDao->findWhere("news_item_id = $newsItemId") as $newsItemTypeMap)
		{
			$newsItemTypeMapDao->delete($newsItemTypeMap);
		}

		$i = 0;
		$totalSaved = 0;
		foreach ($tagArray as $newsType)
		{
			$tagId = CodeLookupUtil::getCode("news_item_tag", $newsType);
			if ($tagId == null) $tagId = CodeLookupUtil::addCode("news_item_tag", $newsType);
			$newsItemTypeMap = new NewsItemTypeMap(0, $newsItemId, $tagId);
			$totalSaved += $newsItemTypeMapDao->save($newsItemTypeMap);
			$i++;
		}

		return $i == $totalSaved;
	}

	// TODO don't make this dependent on the insertion order (i.e. 1 and 2)
	function findAllExternal()
	{
		$newsItemDao = new NewsItemDAO();

		return $newsItemDao->findWhere("visibility = 2", "create_date desc");
	}

	function findAllInternal()
	{
		$newsItemDao = new NewsItemDAO();

		return $newsItemDao->findWhere("visibility = 1", "create_date desc");
	}


	function findAll()
	{
		$newsItemDao = new NewsItemDAO();

		return $newsItemDao->findWhere("", "create_date desc");
	}

	function findRecent($number)
	{
		$newsItemDao = new NewsItemDAO();

		$all = $newsItemDao->findWhere("", "create_date desc");

		$finalList = array();
		for ($i = 0; $i < $number && $i < count($all); $i++)
		{
			array_push($finalList, $all[$i]);
		}

		return $finalList;
	}


	function findByExample($newsItem)
	{
		$newsItemDao = new NewsItemDAO();

		return $newsItemDao->findExample($newsItem);
	}


}

?>
